package com.example.nonggo.view.act;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.LinearSnapHelper;
import androidx.recyclerview.widget.RecyclerView;
import androidx.wear.widget.SwipeDismissFrameLayout;

import com.allen.library.RxHttpUtils;
import com.allen.library.interceptor.Transformer;
import com.blankj.utilcode.util.GsonUtils;
import com.example.nonggo.Constants;
import com.example.nonggo.R;
import com.example.nonggo.adpter.MarketTrendsAdapter;
import com.example.nonggo.api.BaseApi;
import com.example.nonggo.api.MDataObserver;
import com.example.nonggo.bean.Category;
import com.tencent.mmkv.MMKV;

import java.util.ArrayList;
import java.util.List;

public class MarketTrendsActivity extends Activity {
    private MarketTrendsAdapter marketTrendsAdapter;
    private static final String TAG = "MarketTrendsActivity";
    private Category category;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_market_trends);
        // 启动环境变化可用
//        setAmbientEnabled();
        // 设置WindowInsetsListener以适应系统栏
        getWindow().setNavigationBarColor(Color.TRANSPARENT);
        // 隐藏状态栏
        getWindow().getDecorView().setSystemUiVisibility(
                View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
        marketTrendsAdapter = new MarketTrendsAdapter(category -> {
            MarketTrendsActivity.this.category = category;
            TextView btn = findViewById(R.id.btn_next);
            btn.setText(category.getChildren() == null || category.getChildren().isEmpty() ? "完成" : "下一步");
        });
        // 尝试从缓存中获取数据
        fetchCachedData();
        SwipeDismissFrameLayout mainView = findViewById(R.id.main);
        mainView.addCallback(new SwipeDismissFrameLayout.Callback() {
            @Override
            public void onDismissed(SwipeDismissFrameLayout layout) {
                onBackPressed();
            }
        });

        // 设置Back按钮的点击事件
        ImageButton backButton = findViewById(R.id.back_button);
        backButton.setOnClickListener(v -> this.onBackPressed());

        // 设置RecyclerView的适配器或其他初始化操作
        RecyclerView recyclerView = findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setAdapter(marketTrendsAdapter);

        // 添加SnapHelper以实现滚轮效果
        LinearSnapHelper snapHelper = new LinearSnapHelper();
        snapHelper.attachToRecyclerView(recyclerView);
        // 监听滚动事件以更新选中的项
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
                    if (layoutManager != null) {
                        int firstVisibleItemPosition = layoutManager.findFirstVisibleItemPosition();
                        int lastVisibleItemPosition = layoutManager.findLastVisibleItemPosition();
                        if (firstVisibleItemPosition != RecyclerView.NO_POSITION && lastVisibleItemPosition != RecyclerView.NO_POSITION) {
                            marketTrendsAdapter.setSelectedItemPosition(
                                    firstVisibleItemPosition == lastVisibleItemPosition ? firstVisibleItemPosition : firstVisibleItemPosition + 1
                            );
                        }
                    }
                }
            }
        });
        if (isNetworkAvailable()) {
            fetchNetworkData();
        } else {
            fetchCachedData();
        }
        findViewById(R.id.btn_next).setOnClickListener(v -> {

            if (!marketTrendsAdapter.next(category) && category != null) {
                // 跳转到详情
                Intent intent = new Intent(this, AssistantDetailActivity.class);
                intent.putExtra("category", category);
                intent.putExtra("varietyName", category.getLabel());
                startActivity(intent);
            }
            // 滚动到选中项
//            recyclerView.scrollToPosition(marketTrendsAdapter.getSelectedItemPosition());

        });
    }

    private void fetchCachedData() {
        List<Category> categories = new ArrayList<>();
        String cacheDataJson = MMKV.defaultMMKV().getString(Constants.MARKET_TRENDS_DATA, "[]");
        if (!cacheDataJson.isEmpty()) {
            categories = GsonUtils.fromJson(cacheDataJson, new com.google.gson.reflect.TypeToken<List<Category>>() {
            }.getType());
        }
        marketTrendsAdapter.setCategories(categories);
    }

    @Override
    public void onBackPressed() {
        // 当适配器无法后退时，关闭当前活动
        if (!marketTrendsAdapter.prevList(category)) {
            finish();
        }
    }

    private void fetchNetworkData() {
        RxHttpUtils
                .createApi(BaseApi.class)
                .getMarketTrends(MMKV.defaultMMKV().getString(Constants.ACCESS_TOKEN, "0"))
                .compose(Transformer.switchSchedulers(null))
                .subscribe(new MDataObserver<>() {
                    @Override
                    protected void onSuccess(List<Category> data) {
                        MMKV.defaultMMKV().encode(Constants.MARKET_TRENDS_DATA, GsonUtils.toJson(data));
                        marketTrendsAdapter.setCategories(data);
                    }
                });
    }

    private boolean isNetworkAvailable() {
        ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        return activeNetworkInfo != null && activeNetworkInfo.isConnected();
    }

}
